//
//  StringExtention.swift
//  SwiftLearning
//
//  Created by 黄龙 on 2023/12/13.
//

import Foundation
import UIKit
import CryptoKit //md5

extension String {
    public var color: UIColor {
        return UIColor(hexString: self)
    }
    
    public func base64DecodeUrlSafe() -> String? {
        if let _ = self.range(of: ":")?.lowerBound {
            return self //如果已有:，表示该str已为明文，无需再decode
        }
        let base64String = self.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
        let padding = base64String.count + (base64String.count % 4 != 0 ? (4 - base64String.count % 4) : 0)
        if let decodedData = Data(base64Encoded: base64String.padding(toLength: padding, withPad: "=", startingAt: 0), options: NSData.Base64DecodingOptions(rawValue: 0)), let decodedString = NSString(data: decodedData, encoding: String.Encoding.utf8.rawValue) {
            return decodedString as String
        }
        return nil
    }
    
    public func base64DecodeStr() -> String?{
        let base64String = self.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
        let padding = base64String.count + (base64String.count % 4 != 0 ? (4 - base64String.count % 4) : 0)
        if let decodedData = Data(base64Encoded: base64String.padding(toLength: padding, withPad: "=", startingAt: 0), options: NSData.Base64DecodingOptions(rawValue: 0)), let decodedString = NSString(data: decodedData, encoding: String.Encoding.utf8.rawValue) {
            return decodedString as String
        }
        return nil
    }
    
    public func trimSpace()->String{
        return self.trimmingCharacters(in: .whitespaces)
    }
    
    func hl_md5()->String{
        if let messageData = self.data(using: .utf8){
            let digestData = Insecure.MD5.hash (data: messageData) //CryptoKit
            let digestHex = String(digestData.map { String(format: "%02hhx", $0) }.joined().prefix(32))
            return digestHex
        }else{
            return self
        }
    }
}

